import java.util.function.ToDoubleBiFunction;

public class Java1004 {

    public int val;
    public Java1004 next;
    public Java1004 head;


    public Java1004(int val) {
        this.val = val;
    }

    public void creatList() {

        Java1004 node1 = new Java1004(12);
        Java1004 node2 = new Java1004(23);
        Java1004 node3 = new Java1004(34);
        Java1004 node4 = new Java1004(45);
        Java1004 node5 = new Java1004(56);


        node1.next = node2;  //将前一个结点的地址赋予给上一个结点的.next字段
        node2.next = node3;  //从而建立链接
        node3.next = node4;
        node4.next = node5;

        this.head = node1;

    }

    //计算长度
    public int size(){
        Java1004 x = head;
        int count = 0;
        while (x != null){
            count++;
            x = x.next;
        }

        return count;
    }

    //判断是否包含某个值
    public boolean contain(int key){
        Java1004 x = head;

        while (x != null){
            if(x.val == key){    //注意是x.val，x代替head往前走
                return true;
            }
            x = x.next;
        }
        return false;
    }

    public void addFirst(int key){
        Java1004 node = new Java1004(key);

        node.next = head;      //先绑定后面的值，再确定头
        head = node;
    }

    public void addLast(int key){
        Java1004 node = new Java1004(key);
        if(size() == 0)
        {
            head = node;
            return;
        }

        Java1004 x = head;
        while (x.next != null){
            x = x.next;
        }
        x.next = node;
    }

    public void addIndex(int index,int key){
        int len = size();

        //可以自定义一个异常
        if(index < 0 || index > len){
            return;
        }

        //头插
        if(index == 0){
            addFirst(key);
            return;
        }

        //尾插
        if(index == len){
            addLast(key);
            return;
        }

        //中间位置插入
        Java1004 node = new Java1004(key);
        Java1004 cur = searchIndex(index);

        //更严谨的步骤,条件成立以下部分不执行
        if(cur == null){
            return;
        }

        node.next = cur.next;
        cur.next = node;

    }

    public Java1004 searchIndex(int index){
        int len = size();

        if(index < 0 || index > len){
            return null;
        }

        Java1004 cur = head;
        int count = 0;

        while (count != index - 1){
            cur = cur.next;
            count++;
        }

        //返回输入下标前一个结点的地址
        return cur;
    }



    public void show() {
        Java1004 x = head;

        while (x != null){
            System.out.println(x.val);
            x = x.next;
        }
    }


}